package ppp.hhh.webfluxdemo.controller;

import jakarta.annotation.PostConstruct;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ppp.hhh.webfluxdemo.entity.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/user")
public class UserController {
    Map<Long, User> users=new HashMap<>();
    @PostConstruct
    public void init(){
        users.put(Long.valueOf(1),new User(1,"zhangsan",18));
        users.put(Long.valueOf(2),new User(2,"lisi",19));
    }
    /**
     * 获取所有用户
     */
    @GetMapping("/list")
    public Flux<User> getAll(){
        return Flux.fromIterable(users.entrySet().stream().map(e->e.getValue()).toList());
    }
    /**
     * 根据id获取用户
     */
    @GetMapping("/{id}")
    public Mono<User> getById(@PathVariable Long id){
        return Mono.justOrEmpty(users.get(id));
    }
    /**
     * 创建用户
     */
    @PostMapping("")
    public Mono<ResponseEntity<String>> create(User user){
        users.put(user.getId(),user);
        return Mono.just(new ResponseEntity<String>("添加成功", HttpStatus.CREATED));
    }
    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public Mono<ResponseEntity<User>> update(@PathVariable Long id,User user){
        user.setId(id);
        users.put(id,user);
        return Mono.just(new ResponseEntity<>(user, HttpStatus.CREATED));
    }
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<String>> deleteUser(@PathVariable Long id){
        users.remove(id);
        return Mono.just(new ResponseEntity<>("删除成功", HttpStatus.ACCEPTED));
    }
}
